package com.chcit.mobile.mvp.common.model;

import android.app.Application;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chcit.mobile.app.exception.BaseException;
import com.chcit.mobile.app.exception.CodeMsg;
import com.chcit.mobile.common.SPDErrorHandle;
import com.chcit.mobile.helper.HttpClientHelper;
import com.chcit.mobile.mvp.common.contract.CommonContract;
import com.chcit.mobile.mvp.common.api.cache.CommonCache;
import com.chcit.mobile.mvp.common.api.service.CommonService;
import com.chcit.mobile.mvp.common.api.service.UserService;
import com.chcit.mobile.mvp.entity.BpartnerBean;
import com.chcit.mobile.mvp.entity.MonitorCode;
import com.chcit.mobile.mvp.entity.ResultBean;
import com.chcit.mobile.mvp.entity.Statu;
import com.chcit.mobile.mvp.inventory.model.api.InventoryService;
import com.google.gson.Gson;
import com.jess.arms.integration.IRepositoryManager;
import com.jess.arms.mvp.BaseModel;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
import javax.inject.Inject;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import io.rx_cache2.DynamicKey;
import io.rx_cache2.EvictProvider;

public class CommonModel extends BaseModel implements CommonContract.Model {

    @Inject
    public CommonModel(IRepositoryManager repositoryManager) {
        super(repositoryManager);
    }

    @Inject
    Gson mGson;
    @Inject
    Application mApplication;

    //获取供应商信息
    public Observable<List<BpartnerBean>> getBparenerBeans() {
        //使用rxcache缓存,上拉刷新则不读取缓存,加载更多读取缓存
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("accessAll","N");
        return Observable.just(mRepositoryManager
                .obtainRetrofitService(UserService.class)
                .queryBpartners().map(jsonObject1 -> jsonObject1.getJSONArray("rows").toJavaList(BpartnerBean.class)
                ))
                .flatMap((Function<Observable<List<BpartnerBean>>, ObservableSource<List<BpartnerBean>>>)
                        bpartnerBeans -> mRepositoryManager.obtainCacheService(CommonCache.class)
                                .getBpartners(bpartnerBeans)).subscribeOn(Schedulers.io());
    }
    //获取字典
    public Observable<List<Statu>> refList(int id, boolean update) {
        return Observable.just(mRepositoryManager
                .obtainRetrofitService(CommonService.class)
                .refList(id).map(jsonObject1 -> {
                            if (jsonObject1.getTotal() > 0) {
                                return jsonObject1.getRows();
                            } else {
                                throw new BaseException(id + "-没有查询到数据！");
                            }
                        }
                ))
                .flatMap((Function<Observable<List<Statu>>, ObservableSource<List<Statu>>>) status
                        ->
                        mRepositoryManager.obtainCacheService(CommonCache.class)
                                .getStatus(status, new DynamicKey(id), new EvictProvider(update))).subscribeOn(Schedulers.io());
    }


    public Observable<List<MonitorCode>> getMonitorCodes(String method, JSONObject json) {
        return mRepositoryManager.obtainRetrofitService(CommonService.class)
                .getMonitorCodes(method, json)
                .map(responseBean -> {
                    if (responseBean.isSuccess()) {
                        return responseBean.getData().getRows();
                    } else {
                        throw new Exception("请求失败: " + (responseBean.getMsg() == null ? "未知错误！" : responseBean.getMsg()));
                    }

                }).subscribeOn(Schedulers.io());
    }

    public Observable<ResultBean> doConfirm(String method, JSONObject json) {
        return mRepositoryManager.obtainRetrofitService(UserService.class)
                .request(method, json)
                .map(jsonObject -> {
                    ResultBean resultBean = mGson.fromJson(jsonObject.toJSONString(), ResultBean.class);
                    if (resultBean.isSuccess()) {
                        return resultBean;
                    } else {
                        throw new Exception("请求失败: " + resultBean.getMsg());
                    }

                }).subscribeOn(Schedulers.io());
    }
    //获取拒收原因
    public Observable<List<Statu>> queryReasons() {
        return Observable.just(mRepositoryManager
                .obtainRetrofitService(CommonService.class)
                .queryResons().map(jsonObject1 -> {
                            if (jsonObject1.getTotal() > 0) {
                                return jsonObject1.getRows();
                            } else {
                                throw new BaseException("没有查询到拒收原因！");
                            }
                        }
                ))
                .flatMap((Function<Observable<List<Statu>>, ObservableSource<List<Statu>>>) listObservable
                        ->
                        mRepositoryManager.obtainCacheService(CommonCache.class)
                                .queryResons(listObservable)).subscribeOn(Schedulers.io());

    }


    public Observable<JSONObject> requestBySubmit(String method, JSONObject json) {
        return mRepositoryManager.obtainRetrofitService(UserService.class)
                .requestBySubmit(method, json).subscribeOn(Schedulers.io());
    }


    public Observable<JSONObject> requestOnString(String method, JSONObject json) {
        return mRepositoryManager.obtainRetrofitService(UserService.class)
                .requestOnString(method, json)
                .map(result -> {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    if (jsonObject.getBoolean("success")) {
                        return jsonObject.getJSONObject("data");

                    } else {
                        String msg = jsonObject.getString("msg");
                        if (msg != null && !msg.isEmpty()) {
                            throw new Exception(msg);
                        } else {
                            throw new Exception("未知错误！");
                        }
                    }
                }).subscribeOn(Schedulers.io());
    }

    /* productId:1037383
     warehouseId:1000214*/
    @Override
    public Observable<JSONArray> queryUnitPackQty(JSONObject json) {
        return mRepositoryManager.obtainRetrofitService(CommonService.class)
                .queryPackageUnit(json)
                .map(result -> {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    if (jsonObject.getBoolean("success")) {
                        if (jsonObject.getInteger("total") > 0) {
                            return jsonObject.getJSONArray("rows");
                        } else {
                            throw new BaseException("没有查询到包装定数信息！");
                        }

                    } else {
                        String msg = jsonObject.getString("msg");
                        if (msg != null && !msg.isEmpty()) {
                            throw new Exception(msg);
                        } else {
                            throw new Exception("未知错误！");
                        }
                    }
                });
    }

    // {"total":1,"rows":[{"unitPackQty":5,"storagePackageCount":"0"}],"success":true}
    @Override
    public Observable<JSONArray> queryPackageInfo(JSONObject json) {
        return mRepositoryManager.obtainRetrofitService(CommonService.class)
                .queryPackageInfo(json)
                .map(result -> {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    if (jsonObject.getBoolean("success")) {
                        if (jsonObject.getInteger("total") > 0) {
                            return jsonObject.getJSONArray("rows");
                        } else {
                            throw new Exception("没有查询到包装信息！");
                        }

                    } else {
                        String msg = jsonObject.getString("msg");
                        if (msg != null && !msg.isEmpty()) {
                            throw new Exception(msg);
                        } else {
                            throw new Exception("未知错误！");
                        }
                    }
                }).subscribeOn(Schedulers.io());
    }

    @Override
    public Observable<ResultBean> doChecked(JSONObject json) {
        return mRepositoryManager.obtainRetrofitService(InventoryService.class)
                .doCheked(json).subscribeOn(Schedulers.io());
    }
    //检测员工号码
    @Override
    public Observable<JSONArray> checkUserCode(JSONObject json) {
        return mRepositoryManager.obtainRetrofitService(UserService.class)
                .chckUserCode(json)
                .map(result -> {
                    JSONObject resultJson = JSONObject.parseObject(result);
                   if(resultJson.getBoolean("success")){
                        return  resultJson.getJSONArray("rows");
                   }else if(StringUtils.isEmpty(resultJson.getString("msg"))){
                       throw new BaseException(CodeMsg.USER_NO_EXIS);
                   }else{
                       throw new BaseException(resultJson.getString("msg"));
                   }
                }).subscribeOn(Schedulers.io());
    }

    @Override
    public Observable<List<BpartnerBean>> getBparenerBeans(String wareHoseId) {
        return mRepositoryManager.obtainRetrofitService(CommonService.class)
                .getVendor(wareHoseId)
                .map(result -> {
                    if(result.isSuccess()){
                        return  result.getRows();
                    } else{
                        throw new BaseException(result.getMsg());
                    }
                }).subscribeOn(Schedulers.io());
    }

    public  Observable<List<Statu>> queryUsers(String readWrite,String excludeSelf,int userType,int warehouseId) {
        JSONObject data = new JSONObject();
        data.put("readWrite",readWrite);
        data.put("excludeSelf", excludeSelf);
        data.put("userType", userType);
        data.put("warehouseId", warehouseId);

        return Observable.just(mRepositoryManager.obtainRetrofitService(CommonService.class)
                .queryUsers(data).map(baseData -> {
                    if (baseData.isSuccess()) {
                        if (baseData.getTotal() > 0)
                            return baseData.getRows();
                        throw new Exception("没有查询数据");
                    } else {
                        String msg = baseData.getMsg();
                        throw new Exception(msg == null ? "未知错误" : msg);
                    }
                })).flatMap((Function<Observable<List<Statu>>, ObservableSource<List<Statu>>>) stringObservable ->
                        mRepositoryManager.obtainCacheService(CommonCache.class)
                        .queryUsers(stringObservable))
                .subscribeOn(Schedulers.io());



    }

}
